home *** CD-ROM | disk | FTP | other *** search
- #include "filei3.hpp"
-
- // 7 bytes to 8 codes
- int code7to8(unsigned char* s7, int len7, unsigned char* s8)
- {
- if (!s7 || !s8 || len7 <= 0)
- return 0;
- if (len7 > 7)
- len7 = 7;
- unsigned char v = 0;
- for (int i = 0; i < len7; i++)
- {
- v += (((s7[i] >> 7) & 1) << i);
- s8[i+1] = s7[i] & 0x7f;
- }
- s8[0] = v;
- return len7+1;
- }
-
- // 8 codes to 7 bytes
- int code8to7(unsigned char* s8, int len8, unsigned char* s7)
- {
- if (!s7 || !s8 || len8 <= 0)
- return 0;
- if (len8 > 8)
- len8 = 8;
- for (int i = 0; i < len8-1; i++)
- s7[i] = s8[i+1] + (((s8[0] >> i) & 1) << 7);
- return len8-1;
- }
-
- // read bytes from file and produce codes
- int loaddata7(FILE* f, int pos, int len, unsigned char* data7)
- {
- if (!f || len <= 0 || !data7)
- return 0;
- fseek(f, pos, SEEK_SET);
- if (ftell(f) != pos)
- return 0;
- int len7 = 0;
- int n, n8;
- unsigned char buf[7];
- while (len > 0)
- {
- n = 7; if (len < n) n = len;
-
- if (fread(buf, n, 1, f) != 1)
- return 0;
- n8 = code7to8(buf, n, data7);
- data7 += n8;
- len7 += n8;
- len -= n;
- }
- return len7;
- }
-
- // convert codes to bytes and write to file
- int savedata8(FILE* f, unsigned char* data8, int len8)
- {
- int len7 = 0;
- unsigned char buf[7];
-
- if (!f || !data8 || len8 <= 0)
- return 0;
- while (len8 >= 8)
- {
- int n = code8to7(data8, len8, buf);
- if (fwrite(buf, n, 1, f) != 1)
- break;
- len7 += n;
- len8 -= 8;
- }
- return len7;
- }
-